package com.lancoo.znbkxx.teacher.ui.fragment

import android.os.Build
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.adapter.MatcherAdapter
import com.lancoo.znbkxx.teacher.adapter.QuestionAnalysisAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.SubChildVoicePlayer
import com.lancoo.znbkxx.teacher.base.BaseVMFragment
import com.lancoo.znbkxx.teacher.databinding.FmtQuesAnalysisBinding
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import com.lancoo.znbkxx.teacher.utils.TimeUtils
import com.lancoo.znbkxx.teacher.utils.WebStyleUtils
import com.lancoo.znbkxx.teacher.viewmodel.HardSolutionViewModel
import com.lancoo.znbkxx.teacher.widget.voicePlayer.VoicePlayer
import kotlinx.android.synthetic.main.fmt_ques_analysis.*
import java.util.*

/**
 * Created by wealive on 2021/3/2.
 *
 *
 */
class QuesAnalysisFragment : BaseVMFragment<HardSolutionViewModel, FmtQuesAnalysisBinding>(),
        VoicePlayer.PlayListener {
    private lateinit var adapter: QuestionAnalysisAdapter
    private lateinit var matcherAdapter: MatcherAdapter
    private val typeNo by lazy { tkModel.TypeNo }
    private val genre by lazy { tkModel.GenreID }
    private val position by lazy { arguments?.getInt("position") }
    private val tkModel by lazy { viewModel.tkModels.value!![position!!] }
    private val answerType by lazy { tkModel.ChildList[0].ChildAnswerType }
    private val playerList = mutableListOf<SubChildVoicePlayer>()
    private val matcherData = mutableListOf<MultiItemEntity>()
    private val foot by lazy { layoutInflater.inflate(R.layout.item_choice_footer, null) }
    private lateinit var player: VoicePlayer
    override fun setLayoutID(): Int {
        return R.layout.fmt_ques_analysis
    }

    override fun providerContext(): Any? {
        return activity
    }

    override fun providerVMClass(): Class<HardSolutionViewModel>? {
        return HardSolutionViewModel::class.java
    }

    override fun initView() {
        initListenText()
        initPlayer()
        initWebView()
        initAnswer()
        initRecyclerView()
    }

    private fun initListenText() {
        if (tkModel.QuesAudio.Article.isNotBlank()) {
            tv_content.visibility = View.VISIBLE
            tv_content.text = HtmlUtils.setText(
                    getString(R.string.aibk_audioscript, tkModel.QuesAudio.Article))
        } else {
            tv_content.visibility = View.GONE
        }
    }

    private fun initPlayer() {
        if (arrayOf("E", "F", "G", "S", "x").contains(typeNo)) {
            include.visibility = View.VISIBLE
            val audioLength = tkModel.QuesAudio.TimeLength
            val time = TimeUtils.getTime(audioLength)
            include.findViewById<TextView>(R.id.tv_musicTime).text = "00:00/$time"
            val audioPath = tkModel.QuesAudio.Path
            player = VoicePlayer(include.findViewById(R.id.sb_musicProgress), audioPath,
                    include.findViewById(R.id.tv_musicTime),
                    include.findViewById(R.id.iv_audioIcon),
                    true, true, false, this)
            lifecycle.addObserver(player)
        } else {
            include.visibility = View.GONE
        }
    }

    private fun initAnswer() {
        val sb = StringBuffer()
        val sbAnalysis = StringBuffer()
        val childxList = tkModel.ChildList
        if (answerType == 32) {
            childxList[0].ItemList.forEachIndexed { index, subChildItemX ->
                subChildItemX.Size = childxList[0].ItemList.size
                val optionList = childxList[0].ItemList[index].ItemOptionList
                val optionListModified = childxList[0].ItemList[index].ItemOptionList.filter {
                    it.StuCount != "0人" && it.OptionIndex != childxList[0].ItemList[index].ItemAnswer
                }.sortedByDescending {
                    it.StuCount.substring(0, it.StuCount.lastIndexOf("人")).toInt()
                }.toMutableList()
                optionListModified.forEachIndexed { index, optionX ->
                    optionX.Index = index
                    optionX.parentIndex = subChildItemX.SortIndex
                    optionX.parentSize = subChildItemX.Size
                    optionX.size = optionListModified.size
                }
                subChildItemX.ItemOptionList = optionListModified
                optionList.forEach {
                    if (it.OptionIndex == subChildItemX.ItemAnswer) {
                        subChildItemX.StuCount = it.StuCount
                        subChildItemX.Rate = it.Rate
                    }
                }
            }
            matcherData.addAll(childxList[0].ItemList)
        }
        childxList.forEachIndexed { i, childx ->
            if (childx.ChildAnalysis.isEmpty()) {
                sbAnalysis.append("${i + 1}. ...略<br></br>")
            } else {
                if (typeNo != "k" && childx.ChildAnswerType == 2 || childx.ChildAnswerType == 32) {
                    childx.ItemList.forEach { subChildItemX ->
                        sbAnalysis.append(
                                "${subChildItemX.SortIndex}.${subChildItemX.ItemAnalysis}<br></br>")
                    }
                } else if (arrayOf("E", "F", "G", "S", "x").contains(typeNo)) {
                    sbAnalysis.append("${i + 1}.${childx.ItemList[0].ItemAnalysis}<br></br>")
                } else {
                    if (childxList.size == 1) {
                        if (typeNo == "A") {
                            sbAnalysis.append("${childx.ItemList[0].ItemAnalysis}<br></br>")
                        } else {
                            sbAnalysis.append("${childx.ChildAnalysis}<br></br>")
                        }
                    } else {
                        sbAnalysis.append("${i + 1}.${childx.ChildAnalysis}<br></br>")
                    }
                }
            }
            if (arrayOf("m", "N", "U", "b", "Q").contains(typeNo)) {
                val answerList = childx.ChildAnswer.split("\$、")
                answerList.forEachIndexed { j, answer ->
                    val str = answer.replace("$/", "/")
                    if (genre == 23 || genre == 20 || arrayOf("U", "b", "Q").contains(typeNo)) {
                        if (answerList.size <= 1) {
                            sb.append("${i + 1}.$str<br>")
                        } else {
                            sb.append("${j + 1}.$str<br>")
                        }
                    } else {
                        sb.append("${j + 1}.$str  ")
                    }
                }
            } else if (childxList.size == 1) {
                sb.append(childx.ItemList[0].ItemAnswer.replace("$/", "或"))
            } else if (arrayOf("g", "X", "G").contains(typeNo)) {
                sb.append("${i + 1}.${childx.ItemList[0].ItemAnswer.replace("$/", "或")}<br>")
            } else if (typeNo == "k") {
                val itemList = childx.ItemList
                if (itemList.size > 1) {
                    val answerList = mutableListOf<String>()
                    itemList.forEach {
                        answerList.add(it.ItemAnswer)
                    }
                    sb.append("${i + 1}.${answerList.joinToString("、")}<br>")
                } else {
                    sb.append("${i + 1}.${itemList[0].ItemAnswer.replace("$/", "或")}<br>")
                }
            } else {
                sb.append("${i + 1}.${childx.ItemList[0].ItemAnswer.replace("$/", "或")}  ")
            }
        }
        foot.findViewById<TextView>(R.id.tv_answer).text = HtmlUtils.setText(sb.toString())
        if (sbAnalysis.contains("略")) {
            foot.findViewById<TextView>(R.id.tv_analyze).text = "...略"
        } else {
            foot.findViewById<TextView>(R.id.tv_analyze).text =
                HtmlUtils.setText(sbAnalysis.toString())
        }
    }

    private fun initRecyclerView() {
        rv.layoutManager = LinearLayoutManager(requireContext())
        if (answerType == 32) {
            matcherAdapter = MatcherAdapter(matcherData)
            rv.adapter = matcherAdapter
            matcherAdapter.addFooterView(foot)
        } else {
            adapter =
                QuestionAnalysisAdapter(typeNo, genre.toString(), tkModel.ChildList, lifecycle,
                        if (arrayOf("E", "F", "G", "S", "x").contains(typeNo)) player else null)
            rv.adapter = adapter
            adapter.addFooterView(foot)
        }
    }

    private fun initWebView() {
        with(wv.settings) {
            javaScriptEnabled = true
            loadWithOverviewMode = true
        }
        wv.webChromeClient = WebChromeClient()
        wv.addJavascriptInterface(MyJavaScript(), "APP")
        wv.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                val childListSize = tkModel.ChildList.size
                for (a in 0 until childListSize) {
                    val itemListSize = tkModel.ChildList[a].ItemList.size
                    for (b in 0 until itemListSize) {
                        val itemSortIndex = tkModel.ChildList[a].ItemList[b].ItemSortIndex
                        binding.wv.loadUrl(
                                "javascript:setBackGroundColor('" + "blank" + itemSortIndex +
                                        "','" + "#00000000" + "','" + "0px" + "','" + "1px solid #848484" + "')")
                        binding.wv.loadUrl(
                                "javascript:CalledByJavaCodeWithPara('" + "blank" + itemSortIndex
                                        + "','" + "<font color=\"#00afff\">"
                                        + "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp" + "</font>')"
                        )
                    }
                }
                if (Build.BRAND.toLowerCase(Locale.ROOT).contains("oppo")) {
                    binding.wv.loadUrl(
                            "javascript:window.APP.resize(document.body.getBoundingClientRect().height)")
                }
            }
        }
        var body = ""
        var choice = ""
        tkModel.ChildList[0].ChildOptionList.forEach {
            choice += "<b>${it.OptionIndex}.${it.Option}</b><br/>"
        }
        when (typeNo) {
            "C", "D", "H", "k", "P", "Q", "X" -> body = tkModel.QuesBody
            "A", "E", "F", "G", "S", "x", "m", "U", "b", "d", "f" -> body =
                tkModel.ChildList[0].ChildAsk
            "N" -> body = if (genre == 20) tkModel.QuesBody else tkModel.ChildList[0].ChildAsk
            "g" -> body =
                if (genre == 51 || genre == 50 || genre == 27) tkModel.QuesBody else tkModel.ChildList[0].ChildAsk
        }
        if (body == "") {
            wv.visibility = View.GONE
        } else {
            if (answerType == 32) {
                body += choice
            }
            body = body.replace("______________________".toRegex(), "_")
            WebStyleUtils.showWebViewCssStyle(activity, wv, body, false)
        }
    }

    override fun onFinishPlay() {
        if (this::player.isInitialized) {
            player.rePlay()
        }
    }

    override fun onStartPlay() {
        playerList.clear()
        playerList.addAll(adapter.getSubPlayer())
        playerList.forEach { it.pause() }
        if (this::player.isInitialized) {
            player.play()
        }
    }

    inner class MyJavaScript {
        @JavascriptInterface
        fun resize(height: Float) {
            activity?.runOnUiThread {
                val layoutParams = LinearLayout.LayoutParams(
                        resources.displayMetrics.widthPixels,
                        ((height + 80) * resources.displayMetrics.density).toInt()
                )
                binding.wv.layoutParams = layoutParams
            }
        }
    }
}